package com.insurance.Interceptor;

import com.insurance.service.DriverEvalService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

public class SensWordsceptor implements HandlerInterceptor {
    String newWord;
    @Autowired
    private DriverEvalService driverEvalService;
    /**
     * 在进入控制器之前执行
     * 如果是返回false就阻止控制器执行
     */
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        System.out.println("obj:"+o);
        System.out.println("===preHandle===");
        return true;
    }
    /**
     * 控制器执行完成，进入到jsp之前
     * 作用：
     *   日志记录
     *   敏感词语过滤
     * */
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        String word = modelAndView.getModel().get("model").toString();
        List<Map> mapList=driverEvalService.querySensitiveWords();
        String Senswords=mapList.get(1).get("sensitive_words").toString();
         //长度
        String substring = Senswords.substring(0, Senswords.length() - 1);
         //以逗号分割，得出的数据存到 result 里面
        String[] result = substring.split(",");
        for (String r : result) {
            newWord = word.replace(r,"***");
            modelAndView.getModel().put("model",newWord);
            System.out.println("访问的页面："+modelAndView.getViewName());
        }
    }
    /**
     * 在整个jsp成之后执行，
     * 作用：记录过程中出现的异常，可以记录到日志文件中。
     * */
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        //无论是否出现异常，都记录在日志中。
        System.out.println("===afterCompletion==="+e.getMessage());
    }
}
